package com.charging.serviceImpl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.api.impl.WxMaUserServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.charging.bean.Site;
import com.charging.bean.User;
import com.charging.bean.layuiBean.ResultPage;
import com.charging.bean.layuiBean.VoPage;
import com.charging.config.result.ApiResult;
import com.charging.config.result.AppLoginResult;
import com.charging.mapper.UserMapper;
import com.charging.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.charging.util.AuthSign;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 个人信息 服务实现类
 * </p>
 *
 * @author 冯政尚
 * @since 2019-09-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${weixin.appid}")
    String appid = "";
    @Value("${weixin.secret}")
    String secret = "";


    @Override
    public ApiResult login(WxMaJscode2SessionResult result,HttpSession session) {

        String openId = result.getOpenid();
        System.out.println("openId:"+openId);
        String sessionKey = result.getSessionKey();
        //如果已经存在该用户  那么只生成该用户的令牌
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("openid", result.getOpenid());
        User appUsers = this.getOne(queryWrapper);
        System.out.println("appUsers:"+appUsers);
        if (appUsers!=null) {
            try {
                return ApiResult.ok(genTokenData(appUsers.getId(),openId,sessionKey,session));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        //不存在的时候 才保存
        User appUser = new User();
        appUser.setOpenid(openId);
        appUser.setMoeny("0");
        appUser.setCreateTime(System.currentTimeMillis());
        System.out.println("添加:"+appUser);

        if (save(appUser)) {
            try {
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("openid", openId);
                User user = this.getOne(queryWrapper);
                System.out.println("user:"+user);
                    return ApiResult.ok(genTokenData(appUser.getId(),openId,sessionKey,session));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return ApiResult.fail("登陆失败");
    }


    @Override
    public WxMaInMemoryConfig config() {
        WxMaInMemoryConfig config = new WxMaInMemoryConfig();
        config.setAppid(appid);
        config.setSecret(secret);
        return config;
    }

    @Override
    public WxMaService getWxService() {
        WxMaService wxMpService = new WxMaServiceImpl();
        wxMpService.setWxMaConfig(this.config());
        return wxMpService;
    }

    @Override
    public WxMaJscode2SessionResult login(String code) {
        WxMaUserService userService=new WxMaUserServiceImpl(this.getWxService());
        try {
            WxMaJscode2SessionResult info= userService.getSessionInfo(code);
            System.out.println("本次code{}"+code+",登陆的信息：{}"+info.toString());
            System.out.println("info:"+info);
            return info ;
        } catch (WxErrorException e) {
            e.printStackTrace();
            return new WxMaJscode2SessionResult();
        }
    }

    /**
     * 生成数据  ID 和TOken 给前端
     * @param id
     * @param openId
     * @param sessionKey
     * @return
     * @throws UnsupportedEncodingException
     */
    private AppLoginResult genTokenData(Long id, String openId, String sessionKey, HttpSession session) throws UnsupportedEncodingException {
        AppLoginResult appLoginResult=new AppLoginResult();
        appLoginResult.setId(id);
        appLoginResult.setToken(AuthSign.sign(openId,sessionKey) );

        if(appLoginResult!=null){

            session.setAttribute("appLoginResult",appLoginResult.getToken());
        }
        System.out.println("appLoginResult:"+appLoginResult);
        return appLoginResult ;
    }


    /**
     * @param voPage
     * @return 后台查询
     */
    @Override
    public ResultPage<User> selectMyPage(VoPage voPage) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1) * voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        List<User> list = baseMapper.selectMyPage(paramMap);
        Integer count = baseMapper.countMyPage(paramMap);
        ResultPage<User> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }



}
